package com.heaven.jane.sourcegenerator.business.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * OAuth2.0配置 资源服务器配置 授权服务器配置
 * 
 * OAuth2的基础学习参考此博客
 * http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html
 * 
 * @author heaven
 *
 */
@Configuration
public class OAuth2ServerConfig {

	/**
	 * 资源id
	 */
	private static final String RESOURCE_ID = "order";

	/**
	 * 资源服务器配置
	 * @author heaven
	 *
	 */
	@Configuration
	@EnableResourceServer
	protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

		/**
		 * 设置资源服务器的配置，需要至少配置资源id,不同的资源实例通过不同的资源id来区分,在终端授权的时候可以通过这个id来控制终端可以访问那些资源
		 */
		@Override
		public void configure(ResourceServerSecurityConfigurer resources) {
			resources.resourceId(RESOURCE_ID).stateless(true);
		}

		/**
		 * 配置资源服务器受保护资源的访问规则
		 */
		@Override
		public void configure(HttpSecurity http) throws Exception {
			http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().requestMatchers()
					.anyRequest().and().anonymous().and().authorizeRequests().antMatchers("/order/**").authenticated();
		}
	}

	/**
	 * 授权服务器配置
	 * @author heaven
	 *
	 */
	@Configuration
	@EnableAuthorizationServer
	protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
		
		@Autowired
		AuthenticationManager authenticationManager;
		
		@Autowired
		RedisConnectionFactory redisConnectionFactory;

		@Override
		public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
			// 配置两个客户端,一个用于password认证一个用于client认证
			clients.inMemory().withClient("client_1").resourceIds(RESOURCE_ID)
					.authorizedGrantTypes("client_credentials", "refresh_token").scopes("select").authorities("client")
					.secret("123456").and().withClient("client_2").resourceIds(RESOURCE_ID)
					.authorizedGrantTypes("password", "refresh_token").scopes("select").authorities("client")
					.secret("123456");
		}

		@Override
		public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
			endpoints.tokenStore(new RedisTokenStore(redisConnectionFactory))
					.authenticationManager(authenticationManager)
					.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
		}

		@Override
		public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
			// 允许表单认证
			oauthServer.allowFormAuthenticationForClients();
		}
	}

	@Bean
	PasswordEncoder passwordEncoder() {
		return NoOpPasswordEncoder.getInstance();
	}
}
